<template>
  <el-dialog
    :model-value="visible"
    :title="data.id != undefined ? '修改部门' : '新增部门'"
    width="600"
    :close-on-click-modal="false"
    @close="cls"
  >
    <el-form
      ref="formRel"
      :model="data"
      :rules="rules"
      label-width="100px"
      style="max-width: 600px"
    >
      <el-form-item label="上级部门">
        <el-input v-model="data.parentName" disabled />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="data.name" />
      </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="default" @click="cls">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { da } from "element-plus/es/locales.mjs";
import { ref, reactive } from "vue";
import { func } from "vue-types";
import { saveDept, updateDept } from "@/api/dept.js";
// 在你的组件代码中添加
import { ElMessage } from "element-plus";

//表单引用
const formRel = ref(null);

const data = ref({
  parentId: 0,
  parentName: "",
  name: ""
});
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits(["close", "refresh"]);
//表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
});

function cls() {
  emits("close");
}
//保存
async function save() {
  //验证规则 为false时，不会触发表单提交
  const valid = await formRel.value.validate(() => {});
  if (!valid) return;
  let res;
  if (data.value.id != undefined) {
    //编辑部门
    res = await updateDept(data.value);
  } else {
    //新增部门
    res = await saveDept(data.value);
  }
  //保存部门

  if (res.code === 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    //刷新部门列表
    emits("refresh");
    cls();
  }
}

function init(parentId, parentName, id, name) {
  if (id != undefined) {
    //编辑部门
    data.value.name = name;
    data.value.id = id;
  } else {
    //新增部门
    data.value.name = "";
    delete data.value.id;
  }

  data.value.parentId = parentId;
  data.value.parentName = parentName;
}
defineExpose({ init });
</script>

<style scoped></style>
